package xyz.honeysuccess;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Honey
 * @date 2021/12/23
 */
public class UploadFile {

    private static final Map<String, String> MimeType = new HashMap<String, String>(){{
        put("jpg", "image/jpeg");
        put("txt", "text/html");
    }};

    public static void main(String[] args) {
        try {
            String uuid = upLoad("http://localhost:8080/file/upload","D:\\selfFile\\侯成功.jpg");
            System.out.println(uuid);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件上传
     * @param address 服务器http地址
     * @param fileName  文件路径
     * @throws Exception
     * @return
     */
    public static String upLoad(String address, String fileName) throws Exception {
        if(null == address) {
            throw new NullPointerException("address is null .");
        }
        if(null == fileName) {
            throw new NullPointerException("FileName is null.");
        }

        try {
            // 换行符
            final String newLine = "\r\n";
            final String boundaryPrefix = "--";
            // 定义数据分隔线
            String BOUNDARY = "========7d4a6d158c9";
            // 服务器的域名
            URL url = new URL(address);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置为POST情
            connection.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            // 设置请求头参数
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("Content-Type", "image/jpeg; boundary=" + BOUNDARY);
            OutputStream out = new DataOutputStream(connection.getOutputStream());
            // 上传文件
            File file = new File(fileName);
            StringBuilder sb = new StringBuilder();
            sb.append(boundaryPrefix);
            sb.append(BOUNDARY);
            sb.append(newLine);
            // 文件参数,photo参数名可以随意修改
            sb.append("Content-Disposition: form-data;name=\"photo\";filename=\"" + fileName + "\"" + newLine);
            sb.append("Content-Type:application/octet-stream");
            // 参数头设置完以后需要两个换行，然后才是参数内容
            sb.append(newLine);
            sb.append(newLine);
            // 将参数头的数据写入到输出流中
            out.write(sb.toString().getBytes());

            // 数据输入流,用于读取文件数据
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            byte[] bufferOut = new byte[1024];
            int bytes = 0;
            // 每次读1KB数据,并且将文件数据写入到输出流中
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            // 最后添加换行
            out.write(newLine.getBytes());
            in.close();
            // 定义最后数据分隔线，即--加上BOUNDARY再加上--。
            byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine).getBytes();
            // 写上结尾标识
            out.write(end_data);
            out.flush();
            out.close();
            connection.connect();

            int responseCode = connection.getResponseCode();
            if (responseCode >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + responseCode);
            }
            if (responseCode == HttpURLConnection.HTTP_OK) {
                System.out.println(connection.getResponseMessage());
            }
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        }
        return "123";
    }


}
